#include <Event.hpp>
#include <EventSender.hpp>
#include <EventReceiver.hpp>
#include "stl_impl_eds.hpp"

EventReceiver::EventReceiver()
  :_impl( new stl_impl_eds<sender_struct>() )
{}

EventReceiver::~EventReceiver()
{
  cleanAllListener();

  stl_impl_eds<sender_struct>* __p = dynamic_cast< stl_impl_eds<sender_struct>* >(_impl);
  delete __p;
}

void EventReceiver::listenEvent( long _id, EventSender *_sender, EventHandler _listener)
{
  // 尝试往EventSender结构里面加入事件监听，如果成功了，就在EventReceiver里面加入事件监听结构，否则什么都不做
  bool __success = _sender->add_event_dispatch_struct( _id, this, _listener);

  if( __success )
    {
      sender_struct rcv_struct;
      rcv_struct.listenningSender = _sender;
      rcv_struct.eventHandler = _listener;
      _impl->add_node( _id, rcv_struct );
    }
}

void EventReceiver::nolistenEvent( long _id, EventSender *_sender, EventHandler _listener )
{
  if( _sender->has_event_dispatch_struct(_id, this, _listener) )
    {
      _sender->del_event_dispatch_struct(_id, this, _listener);

      sender_struct __rcv_struct;
      __rcv_struct.listenningSender = _sender;
      __rcv_struct.eventHandler = _listener;
      _impl->del_node( _id, __rcv_struct );
    }
}

bool EventReceiver::hasListener( long _id )
{
  return _impl->has_node(_id);
}

void EventReceiver::do_clean_sender( void *_arg, long _id, const EventReceiver::sender_struct &_struct )
{
  _struct.listenningSender->del_event_dispatch_struct(_id, static_cast<EventReceiver*>(_arg), _struct.eventHandler);
}

void EventReceiver::cleanAllListener( void )
{
  _impl->for_each( do_clean_sender, this );
}

bool operator<( const EventReceiver::sender_struct &a, const EventReceiver::sender_struct &b)
{
  unsigned int __a, __b;
  __a = reinterpret_cast<unsigned int>(a.listenningSender);
  __b = reinterpret_cast<unsigned int>(b.listenningSender);
  if( __a == __b )
    {
      __a = (int&)a.eventHandler;
      __b = (int&)b.eventHandler;
    }

  return __a  < __b;
}
